﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DBBaseServer.Entities;
using System.Data.SqlClient;
using Microsoft.Data.SqlClient;
using SqlSugar;
using DbType = SqlSugar.DbType;
using YJTTool.DBBaseServer.Entities;

namespace DBBaseServer.Configurations
{
    public class SqlSugarConfiguration
    {
        private static SqlSugarClient _dbInstance;

        /// <summary>
        /// 连接数据库
        /// </summary>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public static SqlSugarClient GetInstance()
        {
            if (_dbInstance == null)
            {
                lock (typeof(SqlSugarConfiguration))  // 双重锁定保证线程安全
                {
                    if (_dbInstance == null)
                    {
                        _dbInstance = new SqlSugarClient(new ConnectionConfig
                        {
                            // 连接字符串
                            ConnectionString = "Data Source=.;Initial Catalog=YJTTool;User Id=shao-jsh;Password=aa199789..;Encrypt=True;TrustServerCertificate=True;",
                            DbType = DbType.SqlServer,  // 选择数据库类型
                            InitKeyType = InitKeyType.Attribute, // 使用实体的特性初始化表结构
                        });
                    }
                    // 检查数据库连接
                    if (!CheckDatabaseConnection(_dbInstance))
                    {
                        throw new Exception("数据库连接失败！");
                    }
                    InitTables();
                }
            }
            return _dbInstance;
        }

        /// <summary>
        /// 检查数据库连接是否成功
        /// </summary>
        /// <param name="db"></param>
        /// <returns></returns>
        private static bool CheckDatabaseConnection(SqlSugarClient db)
        {
            try
            {
                // 尝试执行一个简单的查询来验证连接是否正常
                var result = db.Ado.GetDataTable("SELECT 1");
                return result != null;
            }
            catch (Exception ex)
            {
                // 捕获异常并输出错误信息
                Console.WriteLine($"数据库连接失败: {ex.Message}");
                return false;
            }
        }

        /// <summary>
        /// 初始化表
        /// </summary>
        private static void InitTables() 
        {
            _dbInstance.CodeFirst.InitTables(typeof(userinfo));
            _dbInstance.CodeFirst.InitTables(typeof(userconfig));
        }

    }
}
